package com.potenza.training.reply.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.potenza.training.reply.config.IKAnalyzerUtil;
import com.potenza.training.reply.config.IdWorker;
import com.potenza.training.reply.dao.ReplyRecordDao;
import com.potenza.training.reply.entity.*;
import com.potenza.training.reply.feign.SysServiceFegin;
import com.potenza.training.reply.service.*;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;


@Service("replyRecordService")
public class ReplyRecordServiceImpl extends ServiceImpl<ReplyRecordDao, ReplyRecordEntity> implements ReplyRecordService {

    @Resource
    private ReplyRecordDao replyRecordDao;

    @Resource
    private SysServiceFegin sysServiceFegin;

    @Resource
    private SubjectReplyService subjectReplyService;

    @Resource
    private ReplySubjectRecordService replySubjectRecordService;

    @Resource
    private SubjectService subjectService;

    @Resource
    private KeyWordService keyWordService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ReplyRecordEntity> page = this.page(
                new Query<ReplyRecordEntity>().getPage(params),
                new QueryWrapper<ReplyRecordEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    @Transactional
    public void saveReply(Map map) {
        //答题用户
        R info = sysServiceFegin.info();
        Map user = (Map) info.get("user");

        //开始答题时间
        ObjectMapper objectMapper = new ObjectMapper();
        String parse = (String) map.get("beginTime");
        Date beginTime = objectMapper.convertValue(parse,Date.class);
        Date endTime = new Date();

        //获取答辩室
        Map replyGroupEntityMap = (Map) map.get("home");
        ReplyGroupEntity replyGroupEntity = new ReplyGroupEntity(Long.valueOf((Integer) replyGroupEntityMap.get("id")),(String) replyGroupEntityMap.get("replyName"),(Integer) replyGroupEntityMap.get("isStart"));


        //根据答辩室id获取该答辩室下所有的题，算出每道题多少分
        List<SubjectEntity> byGroupId = subjectReplyService.findByGroupId(replyGroupEntity.getId());

        //生成的唯一标识
        String replyId = String.valueOf(new IdWorker().nextId());

        //总分
        Double replySouton = 0.00;

        //每题的记录
        List<Map> formList = (List) map.get("form");
        for (Map o : formList) {
            ReplyRecordEntity replyRecordEntity = new ReplyRecordEntity();

            replyRecordEntity.setBeginDate(beginTime);
            replyRecordEntity.setEndDate(endTime);
            replyRecordEntity.setUid(Long.valueOf((Integer) user.get("userId")));
            replyRecordEntity.setHomeId(replyGroupEntity.getId());
            replyRecordEntity.setResultAnswer((String) o.get("standardAnswer"));

            replyRecordEntity.setSubjectId(Long.valueOf((Integer) o.get("id")));
            replyRecordEntity.setReplyId(replyId);

            //视频上传地址路径
            replyRecordEntity.setUrlVideo((String) o.get("urlVideo"));
            replyRecordEntity.setUrlData((String) o.get("urlData"));

            /**
             * 算出用户的成绩
             */
            //将我的答案拆分
            Double couton = 0.00;
           List<String> resultAnswerList = null;
           try {
             resultAnswerList = IKAnalyzerUtil.cut(replyRecordEntity.getResultAnswer());
          } catch (IOException e) {
               e.printStackTrace();
           }
            Set<String> list = new HashSet<>(resultAnswerList);

            //根据题目id查找对应分词表数据
            List<KeyWordEntity> keyWordEntityList = keyWordService.findbyid(Long.valueOf((Integer) o.get("id")));

            for (KeyWordEntity keyWordEntity : keyWordEntityList) {

                Integer groups = keyWordEntity.getGroups();
                String keyWordName = keyWordEntity.getKeyWordName();

                List<Cs> cs = JSON.parseArray(keyWordName, Cs.class);
                int fengs = groups/cs.size();

                if(couton<=100.00){
                    for (Cs c1 : cs) {
                        for (String s : list) {
                            if(s.equals(c1.getKeyWordName())){
                                couton = fengs+couton;
                            }
                        }
                    }
                }
            }

            System.err.println("本次分数：" + couton);

            //存入答辩记录表
            replyRecordEntity.setScore(couton);
            this.save(replyRecordEntity);

            replySouton += couton;
        }

        replySouton = replySouton/formList.size();

        //将分数存入成绩单
        ReplySubjectRecordEntity replySubjectRecordEntity = new ReplySubjectRecordEntity();
        replySubjectRecordEntity.setReplyScore(replySouton);
        replySubjectRecordEntity.setReplyId(replyId);
        replySubjectRecordEntity.setUid(Long.valueOf((Integer) user.get("userId")));
        replySubjectRecordEntity.setHomeId(replyGroupEntity.getId());
        replySubjectRecordEntity.setBeginTime(beginTime);
        replySubjectRecordEntity.setEndTime(endTime);

        replySubjectRecordService.save(replySubjectRecordEntity);
    }

    @Override
    public List<ReplyRecordEntity> findReplyId(String replyId) {
        QueryWrapper<ReplyRecordEntity> query = new QueryWrapper<>();
        query.lambda().eq(ReplyRecordEntity::getReplyId,replyId);
        return list(query);
    }

    @Override
    public Page<ReplyRecordEntity> queryPage(Map<String, Date> params, Integer page, Integer size) {
        //获取当前登录用户数据查询
        R info = sysServiceFegin.info();
        Map user = (Map) info.get("user");

        QueryWrapper<ReplyRecordEntity> replyGroupEntityQueryWrapper = new QueryWrapper<>();
        Object begin = params.get("begin");
        Object end = params.get("end");
        replyGroupEntityQueryWrapper.lambda().eq(ReplyRecordEntity::getUid,Long.valueOf(String.valueOf(user.get("userId"))));
        if(!StringUtils.isEmpty(begin) && !StringUtils.isEmpty(end)){
            replyGroupEntityQueryWrapper.lambda().between(ReplyRecordEntity::getBeginDate,begin,end);
        }

        Page<ReplyRecordEntity> pageData = new Page<>();
        pageData.setSize(size);
        pageData.setCurrent(page);

        return replyRecordDao.selectPage(pageData,replyGroupEntityQueryWrapper);
    }
}